package com.acwing.partition10;

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author `RKC`
 * @date 2022/1/9 10:05
 */
public class AC920最优乘车 {

    private static final int M = 110, N = 510, INF = 0x3f3f3f3f;
    private static boolean[][] graph = new boolean[N][N];
    private static int n = 0, m = 0;

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        String[] s = reader.readLine().split("\\s+");
        m = Integer.parseInt(s[0]);
        n = Integer.parseInt(s[1]);
        for (int i = 0; i < m; i++) {
            s = reader.readLine().split("\\s+");
            int[] t = new int[s.length];
            for (int j = 0; j < s.length; j++) t[j] = Integer.parseInt(s[j]);
            //例：[1, 2, 3] 1->2 1->3 2->3
            for (int j = 0; j < t.length - 1; j++) {
                for (int k = j + 1; k < t.length; k++) {
                    graph[t[j]][t[k]] = true;
                }
            }
        }
        int ans = bfs(1, n);
        if (ans == INF) writer.write("NO\n");
        else writer.write((ans - 1) + "\n");
        writer.flush();
    }

    private static int bfs(int start, int end) {
        int[] dist = new int[n + 1];
        for (int i = 1; i <= n; i++) dist[i] = INF;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(start);
        dist[start] = 0;
        while (!queue.isEmpty()) {
            int u = queue.poll();
            for (int i = 1; i <= n; i++) {
                if (dist[i] != INF || !graph[u][i]) continue;
                dist[i] = dist[u] + 1;
                queue.add(i);
            }
        }
        return dist[end];
    }
}
